package com.itheima.reggie.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.*;
import com.itheima.reggie.service.DishService;
import com.itheima.reggie.service.OrderDetailService;
import com.itheima.reggie.service.OrderService;
import com.itheima.reggie.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 菜品管理
 */
@RestController
@RequestMapping("/statistic")
@Slf4j
public class StatisticController {
    @Autowired
    private OrderService orderService;

    @Autowired
    private OrderDetailService orderDetailService;

    @Autowired 
    private DishService dishService;

    @Autowired
    private UserService userService;

    // 概览
    @GetMapping("/overview")
    public R<Map<String, Object>> getOverview() {
        Map<String, Object> data = new HashMap<>();
        // 获取本月新增菜品数
        LambdaQueryWrapper<Dish> dishQueryWrapper = new LambdaQueryWrapper<>();
        dishQueryWrapper.apply("DATE_FORMAT(create_Time,'%Y-%m') = DATE_FORMAT(CURDATE(),'%Y-%m')");
        int monthlyNewDishes = dishService.count(dishQueryWrapper);
        data.put("monthlyNewDishes", monthlyNewDishes);

        // 获取本月新增员工数
        LambdaQueryWrapper<User> employeeQueryWrapper = new LambdaQueryWrapper<>();
        employeeQueryWrapper.apply("DATE_FORMAT(create_Time,'%Y-%m') = DATE_FORMAT(CURDATE(),'%Y-%m')");
        int monthlyNewEmployees = userService.count(employeeQueryWrapper);
        data.put("monthlyNewEmployees", monthlyNewEmployees);

        // 获取今日订单总数
        LambdaQueryWrapper<Orders> orderQueryWrapper = new LambdaQueryWrapper<>();
        orderQueryWrapper.apply("DATE(order_time) = CURDATE()");
        int todayOrders = orderService.count(orderQueryWrapper);
        data.put("todayOrders", todayOrders);

        // 获取营业额
        LambdaQueryWrapper<Orders> revenueWrapper = new LambdaQueryWrapper<>();
        revenueWrapper.select(Orders::getAmount);
        List<Orders> ordersList = orderService.list(revenueWrapper);
        BigDecimal totalRevenue = ordersList.stream()
                .map(Orders::getAmount)
                .reduce(BigDecimal.ZERO, BigDecimal::add);
        data.put("totalRevenue", totalRevenue);
        return R.success(data);
    }


    // 获取热销菜品
    @GetMapping("/hotDishes")
    public R<List<Map<String, Object>>> getHotDishes() {
        // 获取所有订单详情
        LambdaQueryWrapper<OrderDetail> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.select(OrderDetail::getDishId, OrderDetail::getName, OrderDetail::getNumber);
        List<OrderDetail> orderDetails = orderDetailService.list(queryWrapper);

        // 按菜品ID分组并汇总数量
        Map<Long, Integer> dishCountMap = new HashMap<>();
        Map<Long, String>  dishNameMap = new HashMap<>();
        
        for (OrderDetail detail : orderDetails) {
            Long dishId = detail.getDishId();
            if (dishId != null) {
                dishCountMap.merge(dishId, detail.getNumber(), Integer::sum);
                dishNameMap.putIfAbsent(dishId, detail.getName());
            }
        }

        // 转换为List并排序
        List<Map<String, Object>> hotDishes = dishCountMap.entrySet().stream()
                .map(entry -> {
                    Map<String, Object> dish = new HashMap<>();
                    dish.put("dishId", entry.getKey());
                    dish.put("name", dishNameMap.get(entry.getKey()));
                    dish.put("number", entry.getValue());
                    return dish;
                })
                .sorted((a, b) -> ((Integer) b.get("number")).compareTo((Integer) a.get("number")))
                .limit(5)
                .collect(Collectors.toList());

        return R.success(hotDishes);
    }



    // 24小时下单趋势
    @GetMapping("/hourlyOrders")
    public R<List<Map<String, Object>>> getHourlyOrders() {
        // 创建24小时的时间段
        List<Map<String, Object>> hourlyStats = new ArrayList<>();
        for (int i = 0; i < 24; i++) {
            Map<String, Object> hourData = new HashMap<>();
            hourData.put("hour", String.format("%02d:00-%02d:00", i, (i + 1)));
            hourData.put("count", 0);
            hourlyStats.add(hourData);
        }

        // 获取当天订单数据
        LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.select(Orders::getOrderTime)
                .apply("DATE(order_time) = CURDATE()");
        List<Orders> orders = orderService.list(queryWrapper);

        // 统计每小时的订单数量
        for (Orders order : orders) {
            LocalDateTime orderTime = order.getOrderTime();
            int hour = orderTime.getHour();
            Map<String, Object> hourData = hourlyStats.get(hour);
            int currentCount = (Integer) hourData.get("count");
            hourData.put("count", currentCount + 1);
        }

        return R.success(hourlyStats);
    }
}
